package edu.ntu.cloudroid.server;

import edu.ntu.cloudroid.model.policy.AbstractPrivacyPreference;
import edu.ntu.cloudroid.model.profile.ProfileData;
import gwtupload.server.exceptions.UploadActionException;
import gwtupload.server.gae.AppEngineUploadAction;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;

import au.com.bytecode.opencsv.CSVReader;

public class DataUploadServlet extends AppEngineUploadAction
{
	public static Logger logger = Logger.getLogger(DataUploadServlet.class
			.getName());
   public static final String PATH = "data.upload";
   private static final long serialVersionUID = 1L;


   private enum DataUploadType
   {
      DefaultType, PersonsType, LocationsType, NamesType, FriendType
   }

   @Override
   public String executeAction(HttpServletRequest request,
         List<FileItem> sessionFiles) throws UploadActionException
   {
      String response = "";
      int numSuccessful = 0;
      DataUploadType uploadType = DataUploadType.DefaultType;
      List<String[]> entries = new ArrayList<String[]>();

      boolean error = false;
           

      for (FileItem item : sessionFiles) {
         if (item.isFormField()) {
        	 System.out.println(item.getFieldName());
            if (item.getFieldName().equals("uploadType")) {
               try {            	   
                  String uploadTypeString = item.getString("UTF-8");                  
                  try {
                     uploadType = DataUploadType.valueOf(uploadTypeString
                           .trim());
                  } catch (IllegalArgumentException e) {
                     logger.log(Level.SEVERE, "Could not find upload type '"
                           + uploadTypeString + "'");
                     error = true;
                     response = "Failure: The correct upload type was not specified.";
                  }
               } catch (UnsupportedEncodingException e) {
                  logger.log(Level.SEVERE,
                        "Failed to decode using encoding 'UTF-8'. This should never happen.");
                  error = true;
                  response = "Failure: Could not decode content.";
               }
            }
         } else {
            try {
               InputStream csvStream = item.getInputStream();
               CSVReader reader = new CSVReader(
                     new InputStreamReader(csvStream));               
               entries = reader.readAll();
               reader.close();
            } catch (IOException e) {
               logger.log(Level.WARNING,
                     "Could not load data from person file: " + e.getMessage());
               e.printStackTrace();
               response = "Failure: Could not load CSV file." + numSuccessful;
            }
         }
      }

      // Remove files from session because we're done with them.
      removeSessionFileItems(request);

      if (error)
         return response;
      
		long start = System.currentTimeMillis();
		try {
			switch (uploadType) {
			case PersonsType:// Privacy preference
				Uploader.uploadUsersAndPolicies(logger, entries);
				break;
			case FriendType:
				Uploader.uploadFriendRelations(logger, entries);
				break;
			case LocationsType:
				Uploader.uploadData(logger, entries);
				break;
			case NamesType:
				Uploader.uploadNames(logger, entries);
				break;
			}
		} catch (Exception e) {
		}
		;
      
      System.out.println("Upload time = "+(System.currentTimeMillis() - start));
      return response;
   }
}
